//
//  PlayerController.m
//  AVAudioPlayerDemo
//
//  Created by 周文成 on 2018/1/3.
//  Copyright © 2018年 C-LOVE. All rights reserved.
//

#import "PlayerController.h"
#import "MusicPath.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayerView.h"
#import "CLLRCShowView.h"

@interface PlayerController () <AVAudioPlayerDelegate, PlayerViewProtocol>

@property (strong, nonatomic) IBOutlet PlayerView *playerView;
@property (weak, nonatomic) IBOutlet UIView *lcrBackView;
@property (strong, nonatomic)  CLLRCShowView *lcrShowView;

@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, strong) NSTimer *timer;


@end


@implementation PlayerController


+ (instancetype)sharedInstance {
    static PlayerController *object = nil;
    if (! object) {
        object = [[self alloc] init];
    }
    return object;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.playerView.delegate = self;
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    self.lcrShowView = [[CLLRCShowView alloc] initWithFrame:self.lcrBackView.bounds];
    [self.lcrBackView addSubview:self.lcrShowView];
    
    self.playerView.totalSecond = (NSInteger)self.player.duration;
    self.playerView.curentSecond = (NSInteger)self.player.currentTime;
    self.playerView.playing = self.player.playing;
    
    NSString *pathString = [[NSBundle mainBundle] pathForResource:self.title ofType:@"lrc"];
    if(pathString){
        NSURL *url = [NSURL fileURLWithPath:pathString];
        self.lcrShowView.filerUrl = url;
    }
    else {
        self.lcrShowView.filerUrl = nil;
    }
        
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self palyerForIndex:self.selectedIndex];
}

- (NSTimer *)timer {
    if(!_timer){
        _timer = [NSTimer timerWithTimeInterval:.5 target:self selector:@selector(getCurrentPlayerTime) userInfo:nil repeats:YES];
    }
    return _timer;
}



-  (void)palyerForIndex:(NSInteger)index {
    if(self.musicPaths.count < index + 1){
        return;
    }
    NSString *path = [self.musicPaths objectAtIndex:index];
    [self playerWithPath:path];
    self.title = [MusicPath musicNameWithPath:path];
    
    NSString *pathString = [[NSBundle mainBundle] pathForResource:self.title ofType:@"lrc"];
    if(pathString){
        NSURL *url = [NSURL fileURLWithPath:pathString];
        self.lcrShowView.filerUrl = url;
    }
    else {
        self.lcrShowView.filerUrl = nil;
    }
}


- (BOOL)playerWithPath:(NSString *)path {
    NSURL *url = [NSURL fileURLWithPath:path]; 
    if(url == nil) {
        return NO;
    }
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.player.delegate = self;
    [self.player prepareToPlay];
    [self.player play];
    self.playerView.totalSecond = (NSInteger)self.player.duration;
    self.playerView.curentSecond = (NSInteger)self.player.currentTime;
    self.playerView.playing = self.player.playing;
    return YES;
}

/** 获取当前播放时间 */
- (void)getCurrentPlayerTime {
    
    double time = self.player.currentTime;
    self.playerView.curentSecond = (NSInteger)time;
    if(self.lcrShowView.filerUrl){
        self.lcrShowView.currentTime = (NSInteger)time * 1000;
    }
}


/** 下一首 */
- (void)next {
    NSInteger indexBuffer = self.selectedIndex + 1;
    if(self.musicPaths.count > indexBuffer + 1){
        self.selectedIndex = indexBuffer;
    }
    else {
        self.selectedIndex = 0;
    }
}

- (void)persious {
    NSInteger indexBuffer = self.selectedIndex - 1;
    if(indexBuffer > 0){
        self.selectedIndex = indexBuffer;
    }
    else {
        self.selectedIndex = self.musicPaths.count - 1;
    }
}

#pragma mark- ==== delegate ====

/** 更改播放进度 */
- (void)playerToProgress:(float)progress {
    float time = self.player.duration * progress;
    self.player.currentTime = time;
}
- (void)playerViewNext {
    [self next];
}
- (void)playerViewPersious {
    [self persious];
}

- (BOOL)playerViewPlaying {
    if(self.player.playing){
        [self.player pause];
    }
    else {
        [self.player play];
    }
    return self.player.playing;
}


/** 播放完成的时候调用 */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { 
    [self next];
    NSLog(@"%s", __func__);
}

/** 解码错误 */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error {
    NSLog(@"%s", __func__);
}

/** 音频播放过程程中被中断 */
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    NSLog(@"%s", __func__);
}

/** 当中断结束的时候 */
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
    NSLog(@"%s", __func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
